package com.examplemartin.jpademo.service.pur;

import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.dao.PurchaseDao;
import com.examplemartin.jpademo.pojo.po.purchase.PurDetailPO;
import com.examplemartin.jpademo.pojo.po.purchase.PurPO;
import com.examplemartin.jpademo.pojo.po.repository.purchase.PurInDetailPO;
import com.examplemartin.jpademo.pojo.po.repository.purchase.PurInPO;
import com.examplemartin.jpademo.service.purin.PurInService;
import com.examplemartin.jpademo.util.ValidateMember;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.*;

@Service
public class PurchaseService {

    public static Integer PURPO_STATUS_SPARE = 0;
    public static Integer PURPO_STATUS_RUNNING = 1;
    public static Integer PURPO_STATUS_FINISH = 2;

    public static String PURPO_STATUS_SPARE_NAME = "编制...";
    public static String PURPO_STATUS_RUNNING_NAME = "执行...";
    public static String PURPO_STATUS_FINISH_NAME = "结束...";


    public static ArrayList<String> PURPO_STATUS_NAME = new ArrayList<String>((Arrays.asList(PURPO_STATUS_SPARE_NAME,
            PURPO_STATUS_RUNNING_NAME,
            PURPO_STATUS_FINISH_NAME
    )));

    public static ArrayList<Integer> PURPO_STATUS_VALUE = new ArrayList<Integer>((Arrays.asList(PURPO_STATUS_SPARE,
            PURPO_STATUS_RUNNING,
            PURPO_STATUS_FINISH
    )));

    public static Map<Integer, String> PUR_STATUS_MAP = new HashMap<Integer, String>();

    static {
        PUR_STATUS_MAP.put(PURPO_STATUS_SPARE, PURPO_STATUS_SPARE_NAME);
        PUR_STATUS_MAP.put(PURPO_STATUS_RUNNING, PURPO_STATUS_RUNNING_NAME);
        PUR_STATUS_MAP.put(PURPO_STATUS_FINISH, PURPO_STATUS_FINISH_NAME);
    }


    @Resource
    private PurchaseDao purchaseDao;

    @Resource
    private PurInService purInService;

    /**
     * * 1 按生成日期降序
     * * 2 按状态查找
     * 按状态获取采购订单
     */
    public List<PurPO> findByStatus(Integer status) {
        return purchaseDao.findByStatusOrderByCreateTimeDesc(status);
    }

    /**
     * 查找所有采购订单
     * 按生成日期降序排列
     */
    public List<PurPO> findAll() {
        return purchaseDao.findAll(Sort.by("CreateTime").descending());
    }

    /**
     * *
     * 模糊查找  供应商名,订单号 , 状态, 责任人
     * 排序 状态, 要货日期 ,建档日期
     */
    public List<PurPO> findAllBysupplierAndPurNameAndStatusAndUser(String suppliername, String purname, Integer status, String username) {

        Sort bysatus = Sort.by(Sort.Direction.ASC, "status");
        Sort byneed = Sort.by(Sort.Direction.ASC, "need");
        Sort bycreateTime = Sort.by(Sort.Direction.ASC, "createTime");

        Sort and = bysatus.and(byneed).and(bycreateTime);

        List<PurPO> all = purchaseDao.findAll(new Specification<PurPO>() {
            @Override
            public Predicate toPredicate(Root<PurPO> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                Predicate predicate = null;

                // 判断 status 是否为空
                if (!ValidateMember.isEmpty(status)) {
                    Path<Integer> pathstatus = root.get("status");
                    Predicate equalstatus = cb.equal(pathstatus, status);

                    if (predicate == null) {
                        predicate = equalstatus;
                    } else {
                        predicate = cb.and(predicate, equalstatus);
                    }

                }

                // 判断 责任人 姓名 like 是否为空
                if (!ValidateMember.isEmpty(username)) {
                    Path<String> userPOname = root.get("userPO").get("username");
                    Predicate equalname = cb.like(userPOname.as(String.class), "%" + username + "%");

                    if (predicate == null) {
                        predicate = equalname;
                    } else {
                        predicate = cb.and(predicate, equalname);
                    }

                    predicate = cb.and(predicate, equalname);
                }

                // 判断 订单号 like 是否为空
                if (!ValidateMember.isEmpty(purname)) {
                    Path<String> pname = root.get("name");
                    Predicate equalname = cb.like(pname.as(String.class), "%" + purname + "%");
                    if (predicate == null) {
                        predicate = equalname;
                    } else {
                        predicate = cb.and(predicate, equalname);
                    }
                }

                // 判断 供应商 是否为空
                if (!ValidateMember.isEmpty(suppliername)) {
                    Path<String> sname = root.get("supplierPO").get("name");

                    Predicate equalsname = cb.like(sname.as(String.class), "%" + suppliername + "%");
                    if (predicate == null) {
                        predicate = equalsname;
                    } else {
                        predicate = cb.and(predicate, equalsname);
                    }
                }


                return predicate;

            }
        }, and);


        return all;
    }

    /**
     * 保存订单
     */
    public PurPO savePurPO(PurPO purPO) {
        PurPO save = purchaseDao.save(purPO);
        return save;
    }

    /**
     * 按订单号查询
     */
    public PurPO findById(Long id) {
        return purchaseDao.findById(id).get();
    }

    // 查询已入库明细数量
    public Map<String, Object> getpurinlist(Long purid) {
        HashMap<String, Object> ret = new HashMap<>();

        PurPO purPObyId = purchaseDao.findById(purid).get();
        List<PurInPO> purInList = purInService.findAllByPurPO(purPObyId);

        // 已入库 入库单数
        ret.put("purinSum", purInList.size());

        // 入库明细合计
        HashMap<Long, Integer> goodmap = new HashMap<>();

        // 初始化
        List<PurDetailPO> purDetailPOList = purPObyId.getPurDetailPOList();

        for (PurDetailPO purDetailPO : purDetailPOList){
            goodmap.put(purDetailPO.getGoodPO().getId(),0);
        }
        for (PurInPO purInPO : purInList) {
            List<PurInDetailPO> detail = purInPO.getPurInDetailPOList();
            for (PurInDetailPO gooddetail : detail) {
                Long goodid = gooddetail.getGoodPO().getId();
                Integer goodcount = goodmap.get(goodid);
                goodmap.put(goodid,goodcount+ gooddetail.getGoodcount());
            }
        }
        ret.put("goodmap", goodmap);

        return ret;
    }


    public AjaxResult auditPurPOAjax(PurPO newPur) {
        Optional<PurPO> oldOpt = purchaseDao.findById(newPur.getId());
        if (oldOpt == null) {
            return AjaxResult.fail(500, "订单有错误");
        }

        PurPO oldPur = oldOpt.get();

        // 0 编制中
        // 1 运行中
        // 2 结束
        PurPO save = null;
        //0 -> x 可以
        if (oldPur.getStatus() == 0) {
            oldPur.setStatus(newPur.getStatus());
            oldPur.setUpdateTime(new Date());
            save = purchaseDao.save(oldPur);

            if (save == null) {
                return AjaxResult.fail(500, "订单有错误");
            } else {
                return AjaxResult.success(200, save.getName() + ":订单状态转为 " + PUR_STATUS_MAP.get(save.getStatus()), null);
            }
        }


        //1->2 可以
        if (oldPur.getStatus() == 1 && newPur.getStatus() == 2) {
            oldPur.setStatus(newPur.getStatus());
            oldPur.setUpdateTime(new Date());
            save = purchaseDao.save(oldPur);

            if (save == null) {
                return AjaxResult.fail(500, "订单有错误");
            } else {
                return AjaxResult.success(200, save.getName() + ":订单状态转为 " + PUR_STATUS_MAP.get(save.getStatus()), null);
            }
        }

        // 1->0 查有入库单 拒绝
        if (oldPur.getStatus()== 1 && newPur.getStatus() == 0) {
            List<PurInPO> allByPurPO = purInService.findAllByPurPO(oldPur);
            if (allByPurPO != null &&  allByPurPO.size() != 0) {
                return AjaxResult.fail(500, "已有入库,不能重置到编辑状态");
            } else {
                oldPur.setStatus(newPur.getStatus());
                oldPur.setUpdateTime(new Date());
                save = purchaseDao.save(oldPur);
            }

            if (save == null) {
                return AjaxResult.fail(500, "订单有错误");
            } else {
                return AjaxResult.success(200, save.getName() + ":订单状态转为 " + PUR_STATUS_MAP.get(save.getStatus()), null);
            }
        }

        // 2 - >1 查有入库单 通过
        if (oldPur.getStatus() == 2&& newPur.getStatus() ==1) {
            oldPur.setStatus(newPur.getStatus());
            oldPur.setUpdateTime(new Date());
            save = purchaseDao.save(oldPur);

            if (save == null) {
                return AjaxResult.fail(500, "订单有错误");
            } else {
                return AjaxResult.success(200, save.getName() + ":订单状态转为 " + PUR_STATUS_MAP.get(save.getStatus()), null);
            }
        }

        // 2 - >0 查有入库单 通过
        if (oldPur.getStatus()== 2 && newPur.getStatus() == 0) {
            List<PurInPO> allByPurPO = purInService.findAllByPurPO(oldPur);
            if (allByPurPO != null && allByPurPO.size() != 0) {
                return AjaxResult.fail(500, "已有入库,不能重置到编辑状态");
            } else {
                oldPur.setStatus(newPur.getStatus());
                oldPur.setUpdateTime(new Date());
                save = purchaseDao.save(oldPur);
            }

            if (save == null) {
                return AjaxResult.fail(500, "订单有错误");
            } else {
                return AjaxResult.success(200, save.getName() + ":订单状态转为 " + PUR_STATUS_MAP.get(save.getStatus()), null);
            }
        }

        if (save == null) {
            return AjaxResult.fail(500, "订单有错误");
        } else {
            return AjaxResult.success(200, save.getName() + ":订单状态转为 " + PUR_STATUS_MAP.get(save.getStatus()), null);
        }
    }

}
